package com.example.educationcommunity.service;

import com.example.educationcommunity.mapper.UserMapper;
import com.example.educationcommunity.model.User;
import com.example.educationcommunity.model.UserExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    public void createOrUpdate(User user) {
        UserExample example = new UserExample();
        example.createCriteria()
                .andAccountIdEqualTo(user.getAccountId());
        List<User> users = userMapper.selectByExample(example);
        if(users.size()==0)
        {
            user.setGmtCreate(System.currentTimeMillis());
            user.setGmtModified(user.getGmtCreate());
            user.setQuestionCount(0);
            user.setCommentCount(0);
            user.setActive(0);
            userMapper.insert(user);
        }
        else
        {
            User dbUser = users.get(0);
            User upadteUser = new User();
            upadteUser.setAvatarUrl(user.getAvatarUrl());
            upadteUser.setGmtModified(System.currentTimeMillis());
            upadteUser.setName(user.getName());
            upadteUser.setToken(user.getToken());
            UserExample userExample = new UserExample();
            userExample.createCriteria()
                    .andIdEqualTo(dbUser.getId());
            userMapper.updateByExampleSelective(upadteUser, userExample);
        }
    }
}